package com.ververica.cdc.guass.sink.jdbc.internal.executor;

import com.ververica.cdc.guass.sink.jdbc.JdbcStatementBuilder;
import org.apache.flink.annotation.Internal;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.function.Function;

/**
 * Executes the given JDBC statement in batch for the accumulated records.
 */
@Internal
public interface JdbcBatchStatementExecutor<T> {

    /**
     * Create statements from connection.
     */
    void prepareStatements(Connection connection) throws SQLException;

    void addToBatch(T record) throws SQLException;

    /**
     * Submits a batch of commands to the database for execution.
     */
    void executeBatch() throws SQLException;

    /**
     * Close JDBC related statements.
     */
    void closeStatements() throws SQLException;

    static <T, K> JdbcBatchStatementExecutor<T> keyed(
            String sql, Function<T, K> keyExtractor, JdbcStatementBuilder<K> statementBuilder) {
        return new KeyedBatchStatementExecutor<>(sql, keyExtractor, statementBuilder);
    }
    static <T> JdbcBatchStatementExecutor<T> simple(
            String sql, JdbcStatementBuilder<T> paramSetter) {
        return new SimpleBatchStatementExecutor<>(sql, paramSetter);
    }

}
